const { updateRedisValue } = require("../helpers/redisHelper");
const fs = require("fs");
const path = require("path");
const http = require("http");
const https = require("https");
const outputPath = path.join(__dirname, "../bimFiles");

const transform = (req, res) => {
  const { fileList } = req.body;
  let apikey=req.query.apikey
  try {
    const valid = parameterValidate(fileList);
    if (valid) {
      return res.send({
        ...valid,
      });
    }

    const downloadPromises = fileList.map((file) => {
      return new Promise((resolve, reject) => {
        const fileName = file.guid + ".ifc";
        const fileStream = fs.createWriteStream(
          path.join(outputPath,apikey,fileName)
        );
        const protocol = file.filePath.indexOf("https") > -1 ? https : http;
        const request = protocol.get(file.filePath, (response) => {
          response.pipe(fileStream);
          fileStream.on("finish", () => {
            fileStream.close();
            resolve(file);
          });
        });

        request.on("error", (error) => {
          fs.unlink(path.join(outputPath,apikey,fileName), (err) => {
              if (err) {
                console.log('文件删除失败:', err);
              }
              reject(error);
            });
        });
      });
    });

    Promise.all(downloadPromises)
      .then((files) => {
        updateRedisValue(
          "add",
          fileList.map((item) => {
            return { ...item,apikey,status: 0 };
          }),
          () => {
            res.send({
              errmsg: "准备解析",
              result: 0,
            });
          }
        );
      })
      .catch((error) => {
        console.log(error);
        res.send({
          result: -1,
          errmsg: "出错了：" + error,
        });
      });
  } catch (err) {
    res.send({
      result: -1,
      errmsg: "出错了：" + err,
    });
  }
};

function parameterValidate(fileList) {
  const isLackParams = fileList.some(
    (item) => !(item.filePath && item.fileType && item.guid)
  );
  if (isLackParams) {
    return {
      errmsg: "缺少必传参数或参数值不能为空",
      result: -1,
    };
  }
  const supportFileTypes = ["ifc"]; //可解析的模型文件类型

  if (
    fileList.some(
      (item) => !supportFileTypes.includes(item.fileType.toLowerCase())
    )
  ) {
    //检验文件类型
    console.log(
      `文件类型出错了:文件类型只支持后缀名为${supportFileTypes.join(",")}`,
      fileList
    );
    return {
      errmsg: `文件类型出错了:文件类型只支持后缀名为${supportFileTypes.join(
        ","
      )}`,
      result: -1,
    };
  }
}

module.exports = { transform };
